/*******************************************************************************
	App
*******************************************************************************/
namespace Mocha {

public class Application : Gtk.Application {
	private const ActionEntry[] actions = {
		{"new", action_new},
		{"open", action_open},
		{"preferences", action_preferences}
	};

	public Application () {
		Object (
			application_id: APPLICATION_ID,
			flags: ApplicationFlags.HANDLES_OPEN
		);
	}

	public override void startup () {
		base.startup ();

		Intl.setlocale (LocaleCategory.MESSAGES, "");
		Intl.textdomain (GETTEXT_PACKAGE);
		Intl.bind_textdomain_codeset (GETTEXT_PACKAGE, "utf-8");
		Intl.bindtextdomain (GETTEXT_PACKAGE, LANGUAGE_DIR);

		this.add_menu ();
		this.add_action_entries (actions, this);
	}

	public override void activate () {
		this.action_new ();
	}

	public override void open (File[] files, string hint) {
		foreach (var file in files) {
			var editor = new WindowEditor (this, file);
			editor.show_all ();
		}
	}

	/**** Setup ****/
	private void add_menu () {
		var builder = new Gtk.Builder.from_resource ("/com/googlecode/mocha-text-editor/ui/AppMenu.ui");
		var menu = builder.get_object ("root") as Menu;
		this.app_menu = menu;
	}

	/**** Actions ****/
	private void action_new () {
		var editor = new WindowEditor (this, null);
		editor.show_all ();
	}

	private void action_open () {
		var chooser = new Gtk.FileChooserDialog (
			_("Open..."),
			this.active_window,
			Gtk.FileChooserAction.OPEN,
			_("_Cancel"), Gtk.ResponseType.CANCEL,
			_("_Open"), Gtk.ResponseType.ACCEPT
		);

		if (chooser.run () == Gtk.ResponseType.ACCEPT)
			foreach (var uri in chooser.get_uris ()) {
				File file = File.new_for_uri (uri);
				var c_editor = this.active_window as WindowEditor;
				if (c_editor.file == null)
					c_editor.open (file);
				else {
					var editor = new WindowEditor (this, file);
					editor.show_all ();
				}
			}

		chooser.destroy ();
	}
	
	private void action_preferences () {
		var prefs_dialog = new Dialog.Preferences (null);
		prefs_dialog.run ();
		prefs_dialog.destroy ();
	}

	// Entry point
	public static int main (string[] args) {
		return new Application ().run (args);
	}
}

}
/******************************************************************************/
